package com.gaotai.wangfei.exam.util;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * 
 * <p>
 * Description: [bean的工具类]
 * </p>
 * 
 * @author <a href="mailto: wangfei@gaotai.cn">王飞</a>
 * @version $Revision$
 */
public class BeanUtils
{

	//获得对象的set写入方法
	public static Method getWriteMethod(Object beanObj, String name)
	{
		Method method = null;
		//分析bean对象-》beanInfo
		try
		{
			BeanInfo beanInfo = Introspector.getBeanInfo(beanObj.getClass());
			//所有属性的描述器
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			//遍历属性描述器
			if(pds != null)
			{
				for (PropertyDescriptor pd : pds)
				{
					String pName = pd.getName();
					//如果当前属性是需要的属性则获得其set方法
					if(pName.equals(name))
					{
						method = pd.getWriteMethod();
					}
				}
			}
		}
		catch (IntrospectionException e)
		{
			e.printStackTrace();
		}
		if(method == null)
		{
			throw new RuntimeException("请检查" + name + "的set方法是否已经创建!");
		}
		return method;
	}

}
